<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>聊聊天</title>
    <link rel="shortcut icon" href="___PUBLIC__/static/favicon.ico">
    <link href="__PUBLIC__/static/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
    <link href="__PUBLIC__/static/css/font-awesome.min.css?v=4.4.0" rel="stylesheet">
    <link href="__PUBLIC__/static/css/animate.min.css" rel="stylesheet">
    <link href="__PUBLIC__/static/css/style.min.css?v=4.1.0" rel="stylesheet">
    <link href="__PUBLIC__/static/layer/skin/default/layer.css" rel="stylesheet">
</head>
<body class="gray-bg">
<div class="wrapper wrapper-content  animated fadeInRight">
    <div class="row">
        <div class="col-sm-3"></div>
        <div class="col-sm-6">
            <div class="ibox chat-view">
                <div class="ibox-title">
                    <a href="javascript:loginOut();" class="roll-nav roll-right J_tabExit" style="float: right;height: 20px"><i class="fa fa fa-sign-out"></i> 退出</a>
                    <span id="tips">聊天窗口</span>
                </div>
                <div class="ibox-content">
                    <div class="row">
                        <div class="col-md-9 ">
                            <div class="chat-discussion" id="chatbox" style="height: 650px">
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="chat-users">
                                <div class="users-list">
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <div class="chat-message-form">
                                <div class="form-group">
                                    <textarea class="form-control message-input" name="message" placeholder="输入消息内容，按回车键发送" id="message"></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- login box -->
<div class="ibox-content" style="display: none;width:350px;height:150px" id="loginBox">
    <form class="form-horizontal">
        <div class="form-group">
            <label class="col-sm-3 control-label">用户名：</label>

            <div class="col-sm-8">
                <input type="text" placeholder="用户名" class="form-control" id="uname">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-8">
                <button class="btn btn-sm btn-primary m-t-n-xs" type="button" id="lgbtn">登 录</button>
            </div>
        </div>
    </form>
</div>

<script src="__PUBLIC__/static/js/jquery.min.js?v=2.1.4"></script>
<script src="__PUBLIC__/static/js/bootstrap.min.js?v=3.3.6"></script>
<script src="__PUBLIC__/static/layer/layer.js"></script>
<script type="text/javascript">

    var logbox;
    var userinfo;
    $(function(){
        //check login
        userinfo = checkLogin();
        //send message
        document.getElementById('message').addEventListener('keydown',function(e){
            if(e.keyCode!=13) return;
            e.preventDefault();  //取消事件的默认动作
            sendMessage();
            this.value = '';
        });

        //login
        $("#lgbtn").click(function(){
            if( $("#uname").val() == '' ){
                layer.alert('用户名不能为空', {"title":"友情提示", "icon":2});
                return false;
            }
            doLogin( $("#uname").val() );
            layer.close( logbox );
        });

    });

    //检查登录
    function checkLogin(){
		//获取头像
        var avar = parseInt(Math.random() * 10);
        if( avar == 0 ) avar = 1;
        avar = 'a' + avar + '.jpg';
		
		var user_name = '{$Think.session.K-user_name}';
		if(!user_name){
			showLogin();
			return false;
		}else{
			doLogin( user_name );
            layer.close( logbox );
            return '{"uname" : "' + user_name + '", "avar" : "' + avar + '"}';
		}
		
		/*
        var user_info = localStorage.getItem("userInfo");
        if( !user_info || user_info.uname =='undefined' ){
            showLogin();
            return false;
        }else{
            user_info = $.parseJSON( user_info );
            doLogin( user_info.uname );
            layer.close( logbox );
            return user_info;
        }
		*/
    }

    //登录操作
    function showLogin(){

        logbox = layer.open({
            type: 1,
            title:'欢迎加入聊聊天教师室',
            skin: 'layui-layer-demo', //加上边框
            closeBtn: 0, //不显示关闭按钮
            area: ['380px', '200px'], //宽高
            content: $("#loginBox")
        });

    }

    function doLogin( name ){
		$.ajax({
			type:'POST',
			url :'/chat/login',
			data:{
				username:name
			},
			success:function(e){
				
			},
			error:function(e){
				
			}
		})
        //获取头像
        var avar = parseInt(Math.random() * 10);
        if( avar == 0 ) avar = 1;
        avar = 'a' + avar + '.jpg';

        // 创建一个Socket实例
        ws = new WebSocket('ws://112.74.101.58:8080');
        var loading = layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
        ws.onopen = function(){
            console.log("握手成功");
            layer.close(loading);
            //localStorage.setItem('userInfo', '{"uname" : "' + name + '", "avar" : "' + avar + '"}');
			userInfo = '{"uname" : "' + name + '", "avar" : "' + avar + '"}';
			
			userInfo = $.parseJSON( userInfo );
            $("#tips").text('您好：' + name);

            var msg = '{"type" : "1", "user" : "' + name + '", "avar" : "' + avar + '"}';
            ws.send( msg );

        };

        ws.onmessage = function(e){
            var data = $.parseJSON( e.data );
            if( data.type == 2 ){
                tellOnline( data.user );
            }
            if( data.type == 3 ){
                var message = parseMessage( data.user, data.stime, data.avar, data.msg );
                $("#chatbox").append( message );
                var ex = document.getElementById("chatbox");
                ex.scrollTop = ex.scrollHeight;
            }
            if( data.type == 5 ){
                var user_list = showOnlineUser( data.info );
                $(".users-list").html( user_list );
            }
            if( data.type == 6 ){
                tellOutline( data.user );
            }

        };

        ws.onerror = function(){

            layer.close( loading );
            layer.msg( "登录失败", {'time' : 1000});
        };
    }

    //退出登录
    function loginOut(){
        var msg = '{"type" : "4", "msg" : "login out"}';
        ws.send( msg );
        //localStorage.setItem('userInfo', '');
		$.ajax({
			type:'POST',
			url :'/chat/loginout',
			success:function(e){
				console.log(e);
			},
			error:function(e){
				console.log(e);
			}
		})

        layer.load(0, {shade: false}); //0代表加载的风格，支持0-2
        setTimeout( function(){
            window.location.reload();
        }, 2);
    }

    //提示上线
    function tellOnline( name ){
        layer.msg( name + '上线了', {time : 3000});
    }

    //提示下线
    function tellOutline( name ){
        layer.msg( name + '下线了', {time : 1000});
    }

    //发送消息
    function sendMessage(){

        //format date
        Date.prototype.format =function(format)
        {
            var o = {
                "M+" : this.getMonth()+1, //month
                "d+" : this.getDate(), //day
                "h+" : this.getHours(), //hour
                "m+" : this.getMinutes(), //minute
                "s+" : this.getSeconds(), //second
                "q+" : Math.floor((this.getMonth()+3)/3), //quarter
                "S" : this.getMilliseconds() //millisecond
            }
            if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
                    (this.getFullYear()+"").substr(4- RegExp.$1.length));
            for(var k in o)if(new RegExp("("+ k +")").test(format))
                format = format.replace(RegExp.$1,
                        RegExp.$1.length==1? o[k] :
                                ("00"+ o[k]).substr((""+ o[k]).length));
            return format;
        }

        var times = new Date().format("yyyy-MM-dd hh:mm:ss");
        if( userInfo ){
			console.log(userInfo);
            //socket send
            var msg = '{"type" : "3", "user" : "' + userInfo.uname + '", "avar" : "' + userInfo.avar + '", "stime" : "'
                    + times + '", "msg": "' + $("#message").val() + '"}';
           // console.log(msg);
            ws.send( msg );

            var message = parseMessage( userInfo.uname, times, userInfo.avar, $("#message").val() );
            $(".chat-discussion").append( message );
            $("#message").val('');
            //滚动条自动定位到最底端
            var ex = document.getElementById("chatbox");
            ex.scrollTop = ex.scrollHeight;
        }
    }

    //解析消息发送样式
    function parseMessage( user, time, avar, message ){

        var _html = '<div class="chat-message"><img class="message-avatar" src="__PUBLIC__/static/img/' + avar + '" alt="">';
        _html += '<div class="message"><a class="message-author" href="#"> ' + user + '</a>';
        _html += '<span class="message-date"> ' + time + ' </span>';
        _html += '<span class="message-content">' + message + '</span></div></div>';
        return _html;
    }

    //展示在线人员
    function showOnlineUser( info ){
        var _html = '';
        $.each( info, function(k, v){
            if(v.user !='undefined'){
                _html += '<div class="chat-user"><span class="pull-right label label-primary">在线</span>';
                _html += '<img class="chat-avatar" src="__PUBLIC__/static/img/' + v.avar + '" alt=""><div class="chat-user-name">';
                _html += '<a href="#">' + v.user + '</a></div></div>';
            }
        });

        return _html;
    }
</script>
</body>
</html>